package com.example.emergencysystem_user;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.view.MotionEvent;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

public class Emergency extends Activity {
	boolean recState = false;
	String Spass;
	public static final String TAG = "SampleVideoRecorderActivity";
	private static String EXTERNAL_STORAGE_PATH = "";
	private static String RECORDED_FILE = "video_recorded";
	private static int fileIndex = 0;
	private static String filename = "";
	MediaPlayer player;
	MediaRecorder recorder;
	SurfaceHolder holder;
	
	String ip = "27.35.10.20";
	int port = 8080;
	Socket socket;
	ParcelFileDescriptor pfd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.emergency);
		Intent intent = getIntent();
		Spass = intent.getStringExtra("pass");
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		
		// check external storage
        String state = Environment.getExternalStorageState();
        if (!state.equals(Environment.MEDIA_MOUNTED)) {
            Log.d(TAG, "External Storage Media is not mounted.");
        } else {
            EXTERNAL_STORAGE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
        }
 
        // create a SurfaceView instance and add it to the layout
        SurfaceView surface = new SurfaceView(this);
        holder = surface.getHolder();
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		FrameLayout frame = (FrameLayout) findViewById(R.id.videoLayout);
		frame.addView(surface);
		
		Button btn = (Button) findViewById(R.id.recBtn);
		btn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (recState == false) {
					try {
						if (recorder == null) {
							recorder = new MediaRecorder();
						}
						socket = new Socket(InetAddress.getByName(ip), port);
						pfd = ParcelFileDescriptor.fromSocket(socket);

						recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
						recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
						recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
						recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
						recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
						recorder.setVideoSize(320, 240);
						filename = createFilename();

						Log.d(TAG, "current filename : " + filename);
						recorder.setOutputFile(filename);
						recorder.setOutputFile(pfd.getFileDescriptor());
						recorder.setPreviewDisplay(holder.getSurface());
						recorder.prepare();
						recorder.start();
						recState = true;

					} catch (Exception ex) {
						Log.e(TAG, "Exception : ", ex);
						recorder.release();
						recorder = null;
					}
				}
			}
		});

	}


	private String createFilename() {
		fileIndex++;

		String newFilename = "";
		if (EXTERNAL_STORAGE_PATH == null || EXTERNAL_STORAGE_PATH.equals("")) {
			// use internal memory
			newFilename = RECORDED_FILE + fileIndex + ".mp4";
		} else {
			newFilename = EXTERNAL_STORAGE_PATH + "/" + RECORDED_FILE
					+ fileIndex + ".mp4";
		}

		return newFilename;
	}

	@Override
	protected void onDestroy() {

		if (recorder != null) {
			recorder.release();
			recorder = null;
		}
		/*
		if (mPreview.mCamera != null) {
			mPreview.mCamera.release();
			mPreview.mCamera = null;
		}*/
		super.onDestroy();
	}

	// /////////////////////////////////////////////////////////////
	@Override
	public boolean onKeyDown(int KeyCode, KeyEvent event) {

		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			if (KeyCode == KeyEvent.KEYCODE_BACK) {
				CustomDialog customDialog = new CustomDialog(Emergency.this);
				customDialog.show();
			}

		}

		return super.onKeyDown(KeyCode, event);
	}

	class CustomDialog extends Dialog implements OnClickListener {

		EditText pass;
		Button okButton;
		Button cancelButton;
		Context mContext;

		public CustomDialog(Context context) {
			super(context);
			mContext = context;

			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.emergency_dialog);

			pass = (EditText) findViewById(R.id.pass);
			okButton = (Button) findViewById(R.id.button1);
			cancelButton = (Button) findViewById(R.id.button2);

			okButton.setOnClickListener(this);
			cancelButton.setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			if (v == okButton) {
				if (Spass.equals(pass.getText().toString())) {

					if (recState == true) {
						recorder.stop();
						recorder.reset();
						recorder.release();
						recorder = null;

						ContentValues values = new ContentValues(10);

						values.put(MediaStore.MediaColumns.TITLE,
								"RecordedVideo");
						values.put(AudioColumns.ALBUM, "Video Album");
						values.put(AudioColumns.ARTIST, "Mike");
						values.put(MediaColumns.DISPLAY_NAME, "Recorded Video");
						values.put(MediaStore.MediaColumns.DATE_ADDED,
								System.currentTimeMillis() / 1000);
						values.put(MediaStore.MediaColumns.MIME_TYPE,
								"video/mp4");
						values.put(MediaColumns.DATA, filename);

						Uri videoUri = getContentResolver().insert(
								MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
								values);
						if (videoUri == null) {
							Log.d("SampleVideoRecorder", "Video insert failed.");
							return;
						}

						sendBroadcast(new Intent(
								Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, videoUri));

						Intent intent = new Intent(Emergency.this, Main.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
					} else {
						Intent intent = new Intent(Emergency.this, Main.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
					}

				}

				else {
					Toast.makeText(mContext, "비밀번호가 일치하지 않습니다.",
							Toast.LENGTH_SHORT).show();
				}

			} else if (v == cancelButton) {
				dismiss();
			}
		}
	}

}